package com.alipay.app.groupmeal.standard.ui.c;

import static com.alipay.app.groupmeal.standard.constant.ConfigConstant.onOffLine;

import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.TextView;

import com.alipay.app.groupmeal.standard.R;
import com.alipay.app.groupmeal.standard.base.BaseMVCActivity;
import com.alipay.app.groupmeal.standard.bean.AliPayResVo;
import com.alipay.app.groupmeal.standard.bean.FoodBean;
import com.alipay.app.groupmeal.standard.constant.BaseConstant;
import com.alipay.app.groupmeal.standard.constant.ConfigConstant;
import com.alipay.app.groupmeal.standard.http.bean.resp.Result;
import com.alipay.app.groupmeal.standard.offline.bean.FkBean;
import com.alipay.app.groupmeal.standard.offline.bean.OrderBean;
import com.alipay.app.groupmeal.standard.offline.manager.FkBeanManager;
import com.alipay.app.groupmeal.standard.offline.manager.OrderDataManager;
import com.alipay.app.groupmeal.standard.ui.b.SelectPayResPre;
import com.alipay.app.groupmeal.standard.ui.c.abcp.CPayingAbcpActivity;
import com.alipay.app.groupmeal.standard.ui.c.pre.ScanQrMainPre;
import com.alipay.app.groupmeal.standard.ui.c.pre.SelectPayMainPre;
import com.alipay.app.groupmeal.standard.ui.b.util.NFCManager;
import com.alipay.app.groupmeal.standard.ui.b.util.StringUtils;
import com.alipay.app.groupmeal.standard.ui.b.util.WIth;
import com.yzy.voice.VoicePlay;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Action;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.internal.observers.BlockingBaseObserver;

public class SelectPayActivity extends BaseMVCActivity implements NFCManager.OnReceiveNfcTagCallback {


    private final int closeSec = 60;

    private SelectPayMainPre selectMainPre;

    private ScanQrMainPre scanQrMainPre;

    private TextView mTvCloseTime;

    private TextView mTvCloseTimeQr;

    private TextView mTvAmount;

    private TextView stateTv;

    private TextView mBtnFace;

    private TextView mBtnQr;

    Disposable mdDisposable;

    private String amount = "0";
    // NFC读卡
    private NFCManager mNFCManager;

    private String cardsn;

    private SelectPayResPre selectPayResPre;

    public static void startAct(Context context, String amount) {
        Intent intent = new Intent(context, SelectPayActivity.class);
        intent.putExtra("amount", amount);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        if (ConfigConstant.displayType == BaseConstant.DISPLAY_TYPE.T2) {
            return R.layout.activity_select_pay_ft2;
        } else {
            return R.layout.activity_select_pay;
        }
    }

    @Override
    protected void initView() {
        mTvCloseTime = findViewById(R.id.tv_close_time);
        amount = getIntent().getStringExtra("amount");
        mTvAmount = findViewById(R.id.tv_amount);
        mBtnFace = findViewById(R.id.btn_face);
        mBtnQr = findViewById(R.id.btn_Qr);
        stateTv = findViewById(R.id.stateTv);
        mNFCManager = new NFCManager(this);
    }

    @Override
    protected void initData() {
        UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> usbDeviceList = usbManager.getDeviceList();
        for (UsbDevice usbDevice : usbDeviceList.values()) {
            int vid = usbDevice.getVendorId();
            int pid = usbDevice.getProductId();

            // 打印 VID 和 PID
            Log.d("USB Info", "Vendor ID (VID): " + vid);
            Log.d("USB Info", "Product ID (PID): " + pid);
            Log.d("USB Info", "Name:" + usbDevice.getDeviceName());
            Log.d("USB Info", "Device" + usbDevice.getProductName());
            Log.d("USB Info", "String" + usbDevice.toString());


        }

    }

    @Override
    public boolean onKeyEventBack(KeyEvent event) {
        finish();
        return super.onKeyEventBack(event);
    }

    public static List<File> getAllSerialPorts() {
        List<File> serialPorts = new ArrayList<>();

        try {
            BufferedReader reader = new BufferedReader(new FileReader("/proc/tty/drivers"));
            String line;

            while ((line = reader.readLine()) != null) {
                String[] fields = line.split(" +");

                if (fields.length >= 5 && fields[1].startsWith("serial")) {
                    serialPorts.add(new File("/dev/" + fields[4]));
                }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return serialPorts;
    }

    @Override
    protected void dissmissPresnetation() {
        if (selectMainPre != null) {
            selectMainPre.dismiss();
        }

        if (scanQrMainPre != null) {
            scanQrMainPre.dismiss();
        }

        if (selectPayResPre != null) {
            selectPayResPre.dismiss();
        }
    }

    @Override
    public void onBusiness() {
        super.onBusiness();
        mTvCloseTime = selectMainPre.getmTvCloseTime();
        mTvAmount = selectMainPre.getmTvAmount();
        mBtnFace = selectMainPre.getmBtnFace();
        mBtnQr = selectMainPre.getmBtnQr();
        stateTv = selectMainPre.getStateTv();
        mTvCloseTimeQr = scanQrMainPre.getTvCloseTime();
        mBtnQr.setOnClickListener(v -> {
            selectMainPre.dismiss();
            selectMainPre = null;
            scanQrMainPre.setOwnerActivity(this);
            showPresentationAtMain(scanQrMainPre);
        });

        mBtnFace.setOnClickListener(v -> {
            CPayingAbcpActivity.startActForAbcp(mActivity, amount);
            finish();
        });

        mTvAmount.setText(amount);
        selectPayResPre.getAmount().setText("￥" + amount);
        mdDisposable = Flowable.intervalRange(0, closeSec, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        String btnText = (closeSec - aLong) + "秒";
                        mTvCloseTime.setText(btnText);
                        mTvCloseTimeQr.setText(btnText);
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        finish();
                    }
                })
                .subscribe();

    }

    @Override
    public void initPresentation() {
        super.initPresentation();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
        } else {
            getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        }
        if (mMainDisplay != null) {
            selectMainPre = new SelectPayMainPre(SelectPayActivity.this, mMainDisplay);
            scanQrMainPre = new ScanQrMainPre(SelectPayActivity.this, mMainDisplay, amount);
            scanQrMainPre.setOwnerActivity(this);
            selectMainPre.setOwnerActivity(this);
            showPresentationAtMain(selectMainPre);
            scanQrMainPre.setNetRes((aliPayResVoResult, e) -> {
                if (aliPayResVoResult.isSuccess() && aliPayResVoResult.getResult() != null)
                    payRes(aliPayResVoResult.getResult());
            });
        }
        if (mDisplay != null) {
            selectPayResPre = new SelectPayResPre(SelectPayActivity.this, mDisplay);
            registerPresentation(selectPayResPre);
        }
    }

//    private void showPageAboveCanteen() {
//        if (selectMainPre == null) {
//            Display display = selectHaiMaDisplay();
//            if (display != null) {
//                selectMainPre = new SelectPayMainPre(this, display);
//                selectMainPre.setOwnerActivity(this);
//            }
//        }
//        if (selectMainPre != null) {
//            if (selectMainPre.isShowing()) {
//                selectMainPre.dismiss();
//            }
//            selectMainPre.show();
//        }
//    }
//    private Display selectHaiMaDisplay() {
//        Display[] displays = ((DisplayManager) getSystemService(Context.DISPLAY_SERVICE)).getDisplays();
//        for (Display display : displays) {
//            LogUtils.d("selectHaiMaDisplay : " + display.toString());
//            if (display.getDisplayId() == Display.DEFAULT_DISPLAY) {
//                return display;
//            }
//        }
//        return null;
//    }

    @Override
    protected void onDestroy() {
        if (mdDisposable != null && !mdDisposable.isDisposed()) {
            mdDisposable.dispose();
            mdDisposable = null;
        }
        if (selectMainPre != null) {
            selectMainPre.dismiss();
        }
        super.onDestroy();
        mNFCManager.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mNFCManager.dispatch();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mNFCManager.cancelDispatch();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mNFCManager.receiveTag(intent);
    }

    @Override
    public void onReceiveNfcTag(String tag) {
        if (StringUtils.isEmpty(cardsn)) {
            cardsn = tag;
        } else {
            return;
        }

        stateTv.setText("支付中");
        showPresentation(selectPayResPre);
        String orders = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());

        if (!onOffLine) {
            //脱机交易模式
            FkBean fkBean = FkBeanManager.getInstance().getFkByCardSn(tag);
            if (fkBean == null) {
//                toResult(isFace ? 0 : 1, faceToken, amount,
//                        mTradeNo, mSessionId, "", false,
//                        0, "1", "查无此人");
                AliPayResVo aliPayResVo = new AliPayResVo();
                aliPayResVo.setSuccess(false);
                aliPayResVo.setMsg("查无此人");
                payRes(aliPayResVo);
                return;
            }
            OrderBean orderBean = new OrderBean();
            orderBean.setSuccess(true);//在线模式，订单为未知状态，则不是成功状态
            orderBean.setHavePost(false);//在线模式，订单服务器上操作，则表示为上传订单
            orderBean.setAmount(amount);
            orderBean.setTradeNo(String.valueOf(System.currentTimeMillis()));
            orderBean.setCreateTime(new Date());
            orderBean.setCardno(fkBean.getCardno());
            orderBean.setAuthCode(tag);
            orderBean.setUserName(fkBean.getName());
            OrderDataManager.getInstance().insert(orderBean);
            AliPayResVo aliPayResVo = new AliPayResVo();
            aliPayResVo.setSuccess(true);
            aliPayResVo.setFk(fkBean);
            payRes(aliPayResVo);
        } else {
            new WIth(this).cardPayV2(amount, cardsn,
                    orders, orders, 0, new LinkedList<>(), new BlockingBaseObserver<Result<AliPayResVo>>() {
                        @Override
                        public void onNext(@NonNull Result<AliPayResVo> stringResult) {
                            payRes(stringResult.getResult());
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {

                        }
                    });
        }


    }


    public void payRes(AliPayResVo aliPayResVo) {
        if (selectMainPre == null) {
            selectMainPre = new SelectPayMainPre(SelectPayActivity.this, mMainDisplay);
            mTvAmount = selectMainPre.getmTvAmount();
            mTvAmount.setText(amount);
            scanQrMainPre.dismiss();
            showPresentationAtMain(selectMainPre);
        }
        if (aliPayResVo.isSuccess()) {
            selectMainPre.showSuccess(aliPayResVo.getFk());
            selectPayResPre.showSuccess(aliPayResVo.getFk());
            VoicePlay.with(mActivity).success();
            stateTv.setText("支付完成");
            if (mdDisposable != null && !mdDisposable.isDisposed()) {
                mdDisposable.dispose();
                mdDisposable = null;
            }
            mdDisposable = Flowable.intervalRange(0, 4, 0, 1, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnNext((aLong -> {
                        String btnText = (4 - aLong) + "秒";
                        mTvCloseTime.setText(btnText);
                        mTvCloseTimeQr.setText(btnText);
                    }))
                    .doOnComplete(() -> finish())
                    .subscribe();


        } else {
            if (mdDisposable != null && !mdDisposable.isDisposed()) {
                mdDisposable.dispose();
                mdDisposable = null;
            }
            selectMainPre.showError(aliPayResVo.getMsg(), aliPayResVo.getFk());
            selectPayResPre.showError(aliPayResVo.getMsg(), aliPayResVo.getFk());
        }
    }
}
